package org.pine.dictionary.common;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.*;

import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * mvc配置
 * </p>
 *
 * @author pine
 * @since 2024-05-17
 */
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Bean
    public HandlerInterceptor logIdHandlerInterceptor() {
        return new LogIdHandlerInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<InterceptorRegistration> registrations = new ArrayList<>();
        registrations.add(registry.addInterceptor(logIdHandlerInterceptor()));

        for (InterceptorRegistration registration : registrations) {
            registration.addPathPatterns("/**");
            registration.excludePathPatterns("/pine");
            registration.excludePathPatterns(
                    "/rpc/**",
                    "/api/**",
                    "/ct/**",
                    "/test/**",
                    "/static/**",
                    "/static/favicon.ico",
                    "/swagger-resources/**",
                    "/swagger-ui.html/**",
                    "/webjars/**",
                    "/doc.html",
                    "/doc.html#/**",
                    "/v2/api-docs/**",
                    "/user/doRegister",
                    "/user/doLogin"
            );
        }
    }

    /**
     * 处理跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/static/");
    }
}
